import React, {FC} from 'react';
import './index.css';
import {Button, Form, Input, Space} from 'antd';
import {UserAddOutlined} from '@ant-design/icons';
import {Link} from 'react-router-dom';

/**
 * 注册表单类型
 */
type FieldType = {
	// 用户名
	username?: string;
	// 密码
	password?: string;
	// 确认密码
	confirm?: string;
	// 昵称
	nickname?: string;
};

/**
 * 注册页面
 */
const Register: FC = () => {

	/**
	 * 提交表单
	 */
	const onFinish = (values: FieldType) => {
		console.log('onFinish -> values', values);
	};

	return (
		<div className="register">
			<h1 className="register-title">
				<UserAddOutlined/>&nbsp;注册新用户
			</h1>
			<div className="register-form">
				<Form
					labelCol={{span: 6}}
					wrapperCol={{span: 16}}
					onFinish={onFinish}
				>
					<Form.Item<FieldType>
						label="用户名"
						name="username"
						rules={[
							{required: true, message: '请输入用户名！'},
							{type: 'string', min: 4, max: 18, message: '用户名长度在 4-18 之间！'},
							{pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能由字母和数字和下划线组成！'},
						]}
					>
						<Input/>
					</Form.Item>

					<Form.Item<FieldType>
						label="密码"
						name="password"
						rules={[
							{required: true, message: '请输入密码！'},
							{type: 'string', min: 4, max: 18, message: '密码长度在 4-18 之间！'},
						]}
					>
						<Input.Password/>
					</Form.Item>

					<Form.Item<FieldType>
						label="确认密码"
						name="confirm"
						// 依赖于password，password变动会重新触发confirm
						dependencies={['password']}
						rules={[
							{required: true, message: '请输入密码！'},
							({getFieldValue}) => ({
								validator(_, value){
									if(!value || getFieldValue('password') === value){
										return Promise.resolve();
									}else{
										return Promise.reject(new Error('两次密码不一致'));
									}
								}
							}),
						]}
					>
						<Input.Password/>
					</Form.Item>

					<Form.Item<FieldType>
						label="昵称"
						name="nickname"
						rules={[
							{type: 'string', max: 10, message: '昵称长度在 10 个字符之内！'},
						]}
					>
						<Input/>
					</Form.Item>

					<Form.Item
						wrapperCol={{offset: 10, span: 16}}
					>
						<Space>
							<Button
								type="primary"
								htmlType="submit"
							>
								注册
							</Button>
							<Link to="/login" style={{fontSize: 10}}>
								去登录
							</Link>
						</Space>
					</Form.Item>
				</Form>
			</div>
		</div>
	);
};

export default Register;